
template <typename T>
class UnionFindSet
{
public:
    UnionFindSet()
    {
    }

    template <typename TContainer>
    UnionFindSet(const TContainer &container)
    {
        auto begin = container.begin();
        auto end = container.end();
        while (begin != end)
        {
            m[*begin] = *begin;
            ++begin;
        }
    }

    void insert(const T &value)
    {
        if (!m.count(value))
        {
            m[value] = value;
        }
    }

    bool exist(const T &value)
    {
        return m.count(value);
    }

    T find(const T &value)
    {
        if (m[value] == value)
        {
            return value;
        }
        return m[value] = find(m[value]);
    }

    void join(const T &value1, const T &value2)
    {
        if (find(value1) != find(value2))
        {
            m[find(value1)] = find(value2);
        }
    }

private:
    std::unordered_map<T, T> m;
};

class Solution
{
public:
    int latestDayToCross(int row, int col, vector<vector<int>> &cells)
    {
        int day = cells.size();
        UnionFindSet<int> ufs;
        ufs.insert(0);
        ufs.insert(INT_MAX);
        while (day > 0)
        {
            int x = cells[day - 1][0];
            int y = cells[day - 1][1];
            ufs.insert(getCoordinate(x, y));
            if (x > 1 && ufs.exist(getCoordinate(x - 1, y)))
            {
                ufs.join(getCoordinate(x, y), getCoordinate(x - 1, y));
            }
            if (x < row && ufs.exist(getCoordinate(x + 1, y)))
            {
                ufs.join(getCoordinate(x, y), getCoordinate(x + 1, y));
            }
            if (y > 1 && ufs.exist(getCoordinate(x, y - 1)))
            {
                ufs.join(getCoordinate(x, y), getCoordinate(x, y - 1));
            }
            if (y < col && ufs.exist(getCoordinate(x, y + 1)))
            {
                ufs.join(getCoordinate(x, y), getCoordinate(x, y + 1));
            }
            if (x == 1)
            {
                ufs.join(0, getCoordinate(x, y));
            }
            if (x == row)
            {
                ufs.join(INT_MAX, getCoordinate(x, y));
            }
            if (ufs.find(0) == ufs.find(INT_MAX))
            {
                return day - 1;
            }
            --day;
        }
        return 1;
    }
    inline int getCoordinate(int row, int col)
    {
        return row * 100000 + col;
    }
};